package com.zhenyi.search;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class SearchUtils2 {
	final Path path = Paths.get("sss/article/");

	public void start() throws IOException {
		User user = new User();
		user.setId("2");
		user.setTitle("Lucene全文检索");
		user.setContent(
				"Lucene是apache软件基金会4 jakarta项目组的一个子项目，是一个开放源代码的全文检索引擎工具包，但它不是一个完整的全文检索引擎，而是一个全文检索引擎的架构，提供了完整的查询引擎和索引引擎，部分文本分析引擎（英文与德文两种西方语言）。");

		System.out.println(path.toAbsolutePath().toString());
		Directory directory = FSDirectory.open(path);
		Analyzer analyzer = new StandardAnalyzer();

		IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
		indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
		IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
		Document document = new Document();
		document.add(new TextField("id", user.getId(), Field.Store.YES));
		document.add(new TextField("title", user.getTitle(), Field.Store.YES));
		document.add(new TextField("content", user.getContent(), Field.Store.YES));
		indexWriter.addDocument(document);
		indexWriter.close();
	}

	public void add() throws IOException {
		Directory directory = FSDirectory.open(path);
		Analyzer analyzer = new StandardAnalyzer();

		IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
		indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE);

		IndexWriter indexWriter = new IndexWriter(directory, indexWriterConfig);
		BufferedReader bufferedReader = new BufferedReader(
				new FileReader(new File("D:\\workspace\\TestProject\\sss\\article\\stderrout.log")));
		String content = "";
		while ((content = bufferedReader.readLine()) != null) {
			System.out.println(content);
			Document document = new Document();
			document.add(new TextField("logs", content, Field.Store.YES));
			indexWriter.addDocument(document);
		}

		indexWriter.close();
	}

	public void search() throws IOException, ParseException {
		String queryString = "全文检索";

		// 多条件
		// Query q = MultiFieldQueryParser.parse(new String[]{},new
		// String[]{},new StandardAnalyzer());

		Directory directory = FSDirectory.open(path);
		Analyzer analyzer = new StandardAnalyzer();

		IndexReader indexReader = DirectoryReader.open(directory);
		IndexSearcher indexSearcher = new IndexSearcher(indexReader);

		// 单条件
		QueryParser queryParser = new QueryParser("logs", analyzer);
		Query query = queryParser.parse(queryString);

		TopDocs topDocs = indexSearcher.search(query, 10);

		long conut = topDocs.totalHits;
		System.out.println("检索总条数：" + conut);
		ScoreDoc[] scoreDocs = topDocs.scoreDocs;
		for (ScoreDoc scoreDoc : scoreDocs) {
			Document document = indexSearcher.doc(scoreDoc.doc);
			System.out.print("相关度：" + scoreDoc.score + "-----time:" + document.get("time"));
			System.out.println(document.get("logs"));
		}
	}

	public static void main(String[] args) {
		try {
			SearchUtils2 searchUtils = new SearchUtils2();
			// searchUtils.add();
			searchUtils.start();
			searchUtils.search();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
